package com.mickey.rabbitmq;

import com.mickey.domain.MiaoshaOrder;
import com.mickey.domain.MiaoshaUser;
import com.mickey.domain.OrderInfo;
import com.mickey.result.CodeMsg;
import com.mickey.result.Result;
import com.mickey.service.GoodsService;
import com.mickey.service.MiaoshaService;
import com.mickey.service.OrderService;
import com.mickey.util.StringUtil;
import com.mickey.vo.GoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Desc:消息接收者
 * @Author:czx
 * @CreateDate:2019/1/11 0011$ 14:03$
 */
@Service
public class MQReceiver {

    private static Logger logger = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MiaoshaService miaoshaService;

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receiveMiaosha(String message){
        logger.info("get Message:{}",message);
        MiaoshaMessage mm = StringUtil.stringToBean(message,MiaoshaMessage.class);
        MiaoshaUser user = mm.getMiaoshaUser();
        long goodsId = mm.getGoodsId();
        GoodsVO good = goodsService.getGoodsVOByGoodsId(goodsId);
        int stock = good.getStockCount();
        if(stock <= 0){
            return;
        }
        //判断是否已经秒杀过
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
        if(order !=null){
            return;
        }

        miaoshaService.miaosha(user,good);

    }

    /**
     * Direct模式 交换机Exchange
     * @param message
     */
    @RabbitListener(queues = MQConfig.QUEUE)
    public void receive(String message){
        logger.info("get Message:{}",message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message){
        logger.info("topic queue1 Message:{}",message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message){
        logger.info("topic queue2 Message:{}",message);
    }


    @RabbitListener(queues = MQConfig.HEADERS_QUEUE)
    public void receiveHeader(byte[] message){
        logger.info("headers queue Message:{}",new String(message));
    }




}
